//
//  LTools.m
//  CCXYQroject0
//
//  Created by a on 16/9/9.
//  Copyright © 2016年 a. All rights reserved.
//

#import "LTools.h"


@implementation LTools

#pragma mark - alert 提示

+ (void)alertText:(NSString *)text viewController:(UIViewController *)vc
{
    id obj=NSClassFromString(@"UIAlertController");
    if (obj) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:text preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        [alertController addAction:cancelAction];
        
        [vc presentViewController:alertController animated:YES completion:^{
            
        }];
        
    }else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:text delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    
}

+ (void)showMBProgressWithText:(NSString *)text addToView:(UIView *)aView
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:aView animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = text;
    hud.margin = 15.f;
    hud.yOffset = 70;
    hud.opacity = 0.7f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1.5];
}

#pragma mark - NSUserDefault缓存
//存 Bool
+ (void)storage:(BOOL)dataornot ForKey:(NSString *)key
{
    
    @try {
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setBool:NO forKey:key];
        [defaults setBool:dataornot forKey:key];
        [defaults synchronize];
        
    }
    @catch (NSException *exception) {
        
        
    }
    @finally {
        
    }
    
}
//取 Bool
+ (BOOL)storageForKey:(NSString *)key
{
    //取 token
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    if (![defaults boolForKey:key]) {
        return NO;
    }
    
    return [defaults boolForKey:key];
}

//存
+ (void)cache:(id)dataInfo ForKey:(NSString *)key
{
    
    @try {
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:nil forKey:key];
        if ([dataInfo isKindOfClass:[NSNumber class]])
        {
            id a = dataInfo;
            NSString *str = a;
            [defaults setObject:[NSString stringWithFormat:@"%@",str] forKey:key];
            [defaults synchronize];
            return;

        }
        [defaults setObject:dataInfo forKey:key];
        [defaults synchronize];
        
    }
    @catch (NSException *exception) {
        
        
    }
    @finally {
        
    }
    
}



//取
+ (id)cacheForKey:(NSString *)key
{
    //取 token
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dictionary = [defaults dictionaryRepresentation];
    NSArray *array = dictionary.allKeys;
    if ([defaults valueForKey:key] == nil) {
        return @"";
    }
    if (![array containsObject:key])
    {
        return @"";
    }
    return [defaults valueForKey:key];
}

//退出后需要删除的
+ (void)cacheSave:(NSArray *)keyAry
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dic = [defaults dictionaryRepresentation];
    for (id  key in dic)
    {
        if ([keyAry containsObject:key])
        {
            [defaults removeObjectForKey:key];
        }
    }
 
    [defaults synchronize];

}

#pragma - mark 验证邮箱、电话等有效性
/*手机及固话*/
+ (BOOL)isValidateMobile:(NSString *)mobileNum
{
    
    NSString *phoneNumber = @"^((13[0-9])|145|(15[^4,\\D])|(18[0-9])|(17[0,5-9]))\\d{8}$";
    
    NSPredicate *regextesPhoneNumber = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneNumber];
    if ([regextesPhoneNumber evaluateWithObject:mobileNum] == YES)
    {
        return YES;
    }else{
        
        return NO;
    }
}

#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertController *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:_downUrl]];
    }
}

#pragma mark - 版本更新信息
+ (void)versionForAppid:(NSString *)appid Block:(void(^)(BOOL isNewVersion,NSString *updateUrl,NSString *updateContent))version//是否有新版本、新版本更新下地址
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //test FBLife 605673005
    NSString *url = [NSString stringWithFormat:@"https://itunes.apple.com/cn/lookup?id=%@",appid];
    
    NSString *newStr = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *urlS = [NSURL URLWithString:newStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlS cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        if (data.length > 0) {
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:Nil];
            
            NSArray *results = [dic objectForKey:@"results"];
            
            if (results.count == 0) {
                version(NO,@"no",@"没有更新");
                return ;
            }
            //appStore 版本
            NSString *newVersion = [[[dic objectForKey:@"results"] objectAtIndex:0]objectForKey:@"version"];
            NSString *updateContent = [[[dic objectForKey:@"results"] objectAtIndex:0]objectForKey:@"releaseNotes"];
            //本地版本
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *currentVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            NSString *downUrl = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/us/app/id%@?mt=8",appid];
            BOOL isNew = NO;
            if (newVersion && ([newVersion compare:currentVersion] == 1)) {
                isNew = YES;
            }
            version(isNew,downUrl,updateContent);
            
        }else
        {
            NSLog(@"data 为空 connectionError %@",connectionError);
            
            NSString *errInfo = @"暂无网络连接，请稍后重试";
            switch (connectionError.code) {
                case NSURLErrorNotConnectedToInternet:
                    
                    errInfo = @"暂无网络连接，请稍后重试";
                    break;
                case NSURLErrorTimedOut:
                    
                    errInfo = @"网络连接超时";
                    break;
                default:
                    break;
            }
            NSDictionary *failDic = @{@"msg": errInfo};
            NSLog(@"version erro %@",failDic);
        }
    }];
    
}


@end
